﻿//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Query Application Block
//===============================================================================

using System;
using System.Linq;
using System.Data;
using System.Xml.Linq;
using System.Collections.Generic;
using EntLibContrib.Query.Commands;

namespace EntLibContrib.Query.QuickStart.CustomCommands
{
	/// <summary>
	/// Custom file command to create a Basic3 object
	/// </summary>
	public class CreateBasic3ObjectCommand : FileCommand
	{
		#region Constants
		private const string objectElement = "Basic3";
		#endregion

		#region Construction
		/// <summary>
		/// Initializes a new instance of the <see cref="CreateBasic3ObjectCommand"/> class.
		/// </summary>
		public CreateBasic3ObjectCommand()
		{
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Executes a read action.
		/// </summary>
		/// <returns>
		/// a DataSet containing the results of the read action
		/// </returns>
		public override DataSet ExecuteForRead()
		{
			throw new NotImplementedException();
		}

		/// <summary>
		/// Executes a write action.
		/// </summary>
		public override void ExecuteForWrite()
		{
			// read the xml document
			XDocument document = XDocument.Load(DataFile, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);
			// search for an existing Basic3 object with the same Id
			IEnumerable<XElement> elements = document.Descendants(objectElement).Where(a => ((Guid)a.Attribute("Id")) == (Guid)Parameters["Id"].Value);
			// if the Id was not found then add the new object
			if (elements.Count<XElement>() == 0)
			{
				// add the the new basic3 object
				document.Root.Add(new XElement(objectElement,
														new XAttribute("Id", (Guid)Parameters["Id"].Value),
														new XElement("Name", (string)Parameters["Name"].Value),
														new XElement("OwnerId", (Guid)Parameters["OwnerId"].Value),
														new XElement("CreatedIdentityId", (Guid)Parameters["CreatedIdentityId"].Value),
														new XElement("CreatedDate", (DateTime)Parameters["CreatedDate"].Value),
														new XElement("UpdatedIdentityId", ""),
														new XElement("UpdatedDate", ""),
														new XElement("DeletedIdentityId", ""),
														new XElement("DeletedDate", ""),
														new XElement("IsPermanent", false)));
				// save the xml document
				document.Save(DataFile, SaveOptions.None);
			}
		}
		#endregion
	}
}
